<?php
namespace app\admin\controller;

use app\admin\controller\Base;
use app\common\model\AttachMain;
use app\common\model\CommonSlide;
use app\common\model\Cookie;
use app\common\model\PortalArticle;
use app\common\model\PortalShare;
use app\common\model\UserDownloadLog;
use app\common\model\UserDownloadTimes;
use app\common\model\UserMain;
use app\common\model\WebSite;
use think\facade\Db;
use think\facade\Env;
use think\facade\Request;
use think\facade\Validate;
use think\facade\View;

class Portal extends Base
{
    public function index()
    {
        $article_list = PortalArticle::order('article_id', 'desc')->paginate(30);
        return View::assign([
            'article_list' => $article_list,
            'page'         => $article_list->render(),
        ])->fetch();
    }

    public function add_article()
    {
        if (Request::isAjax() && Request::isPost()) {
            $post     = Request::post();
            $validate = Validate::rule([
                'subject' => 'require',
                'message' => 'require',
            ])->message([
                'subject.require' => '文章标题必填',
                'message.require' => '文章内容必填',
            ]);

            if (!$validate->check($post)) {
                return show_error($validate->getError());
            }
            PortalArticle::create($post);
            return show_success('文章添加成功', 'admin/portal/index');
        }
        return View::assign([])->fetch('edit_article');
    }

    public function edit_article($article_id = 0)
    {
        if (!$article = PortalArticle::where('article_id', '=', $article_id)->find()) {
            return show_error('指定数据不存在', 'admin/portal/index');
        }
        if (Request::isAjax() && Request::isPost()) {
            $post     = Request::post();
            $validate = Validate::rule([
                'subject' => 'require',
                'message' => 'require',
            ])->message([
                'subject.require' => '文章标题必填',
                'message.require' => '文章内容必填',
            ]);

            if (!$validate->check($post)) {
                return show_error($validate->getError());
            }
            $article->save($post);
            return show_success('文章编辑成功', 'admin/portal/index');
        }
        return View::assign([
            'article' => $article,
        ])->fetch('edit_article');
    }

    public function delete_article($article_id = 0)
    {
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $data = PortalArticle::where('article_id', '=', $article_id)->find();
        if (empty($data)) {
            return show_error('指定数据不存在');
        }
        $data->delete();
        return show_success('数据删除成功', 'admin/portal/index');
    }

    public function share()
    {
        $share_list = PortalShare::order('share_id', 'desc')->paginate(30);
        return View::assign([
            'share_list' => $share_list,
            'page'       => $share_list->render(),
        ])->fetch();
    }

    public function review_share($share_id = 0)
    {
        if (!$share = PortalShare::where('share_id', '=', $share_id)->find()) {
            return show_error('指定数据不存在', 'admin/portal/share');
        }
        if (Request::isAjax() && Request::isPost() && Request::post('review/d') == 1) {
            return show_success('分享审核成功', 'admin/portal/share');
        }
        return View::assign([
            'share' => $share,
        ])->fetch('review_share');
    }

    public function add_share()
    {
        $web_site_list = WebSite::select();
        return View::assign([
            'web_site_list' => $web_site_list,
        ])->fetch('edit_share');
    }

    public function edit_share($share_id = 0)
    {
        if (!$share = PortalShare::where('share_id', '=', $share_id)->find()) {
            return show_error('指定数据不存在', 'admin/portal/share');
        }
        if (Request::isAjax() && Request::isPost()) {
            $post     = Request::post();
            $validate = Validate::rule([
                'subject' => 'require',
            ])->message([
                'subject.require' => '标题必填',
            ]);

            if (!$validate->check($post)) {
                return show_error($validate->getError());
            }

            $cover = AttachMain::withTrashed()->where('savename', '=', $post['cover'])->find();
            if (empty($cover)) {
                return show_error('请上传封面');
            }
            $cover->delete();
            if (empty($share['reward'])) {
                if ($post['reward']['balance'] > 0) {
                    UserMain::where('uid', '=', $share['uid'])->update(['balance' => Db::raw('balance+' . $post['reward']['balance'])]);
                }
                foreach ($post['reward']['download'] as $site_id => $value) {
                    if ($value['times'] > 0 && $value['out_time'] >= 0) {
                        UserDownloadTimes::create([
                            'uid'      => $share['uid'],
                            'site_id'  => $site_id,
                            'times'    => $value['times'],
                            'from'     => 'share-reward',
                            'summary'  => '分享素材获得奖励',
                            'out_time' => $value['out_time'] == 0 ? 0 : ($value['out_time'] * 3600 + Request::time()),
                            'status'   => 1,
                        ]);
                    }
                }
            }
            $attach = [
                'site_id'        => $post['site_id'],
                'request_url'    => $post['from_url'],
                'response_url'   => $post['from_url'],
                'site_code'      => $post['site_code'],
                'site_code_type' => $post['site_code_type'],
            ];
            $share->save($post);
            $share->attach->save($attach);
            return show_success('数据编辑成功', 'admin/portal/share');
        }
        $web_site_list = WebSite::select();
        return View::assign([
            'web_site_list' => $web_site_list,
            'share'         => $share,
        ])->fetch('edit_share');
    }

    public function delete_share($share_id = 0)
    {
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $data = PortalShare::where('share_id', '=', $share_id)->find();
        if (empty($data)) {
            return show_error('指定数据不存在');
        }
        $data->delete();
        return show_success('数据删除成功', 'admin/portal/share');
    }

    public function download_log()
    {
        $log_list = UserDownloadLog::with(['user'])->order('log_id', 'desc')->paginate(30);
        return View::assign([
            'log_list' => $log_list,
            'page'     => $log_list->render(),
        ])->fetch();
    }

    public function add_download_log()
    {
        return View::assign([])->fetch('edit_download_log');
    }

    public function edit_download_log()
    {
        return View::assign([])->fetch('edit_download_log');
    }

    public function delete_download_log($log_id = 0)
    {
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $data = UserDownloadLog::where('log_id', '=', $log_id)->find();
        if (empty($data)) {
            return show_error('指定数据不存在');
        }
        $data->delete();
        return show_success('数据删除成功', 'admin/portal/download_log');
    }

    public function delete_download_log_all()
    {
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        UserDownloadLog::chunk(100, function ($log_list) {
            foreach ($log_list as $log) {
                $log->delete();
            }
        });
        return show_success('数据删除成功', 'admin/portal/download_log');
    }

    public function slide()
    {
        $slide_list = CommonSlide::order('slide_id', 'desc')->paginate(30);
        return View::assign([
            'slide_list' => $slide_list,
            'page'       => $slide_list->render(),
        ])->fetch();
    }

    public function add_slide()
    {
        if (Request::isAjax() && Request::isPost()) {
            $post = Request::post();
            if (!$file = Request::file('image')) {
                return show_error('请选择图片文件');
            }
            try {
                validate(['image' => 'filesize:2048000|fileExt:jpg,png,bmp'])
                    ->check([$file]);
                $post['image'] = \think\facade\Filesystem::putFile('topic', $file);
            } catch (think\exception\ValidateException $e) {
                return show_error($e->getMessage());
            }
            $post['image'] = \think\facade\Filesystem::putFile('topic', $file);
            CommonSlide::create($post);
            return show_success('轮播图添加成功', 'admin/portal/slide');
        }
        return View::assign([])->fetch('edit_slide');
    }

    public function edit_slide($slide_id = 0)
    {
        if (!$slide = CommonSlide::where('slide_id', '=', $slide_id)->find()) {
            return show_error('指定数据不存在', 'admin/portal/slide');
        }
        if (Request::isAjax() && Request::isPost()) {
            $post = Request::post();
            if ($file = Request::file('image')) {
                try {
                    validate(['image' => 'filesize:2048000|fileExt:jpg,png,bmp'])
                        ->check([$file]);
                    $post['image'] = \think\facade\Filesystem::putFile('topic', $file);
                } catch (think\exception\ValidateException $e) {
                    return show_error($e->getMessage());
                }
                $post['image'] = \think\facade\Filesystem::putFile('topic', $file);
            }

            $slide->save($post);
            return show_success('轮播图编辑成功', 'admin/portal/slide');
        }
        return View::assign([
            'slide' => $slide,
        ])->fetch('edit_slide');
    }

    public function delete_slide($slide_id = 0)
    {
        if (!Request::isAjax()) {
            return show_error('请求类型错误');
        }
        $data = CommonSlide::where('slide_id', '=', $slide_id)->find();
        if (empty($data)) {
            return show_error('指定数据不存在');
        }
        $data->delete();
        return show_success('数据删除成功', 'admin/portal/slide');
    }

    public function cookie_set(){
        if (!Request::isAjax()) {
            return View::fetch();
        }

        $post = Request::post();

        $content     = [];
        $cookie_data = '# Netscape HTTP Cookie File' . PHP_EOL;
        $cookie_data .= '# https://curl.haxx.se/docs/http-cookies.html' . PHP_EOL;
        $cookie_data .= '# This file was generated by libcurl! Edit at your own risk.' . PHP_EOL . PHP_EOL;
        foreach (explode(';', $post['content']) as $value) {
            $value   = trim($value);
            $first_k = stripos($value, '=');
            if ($first_k === false) {
                continue;
            }
            $cookie_key = trim(substr($value, 0, $first_k));
            $cookie_val = trim(substr($value, $first_k + 1));

            if (substr($cookie_key, 0, 7) == 'Hm_lvt_' || substr($cookie_key, 0, 8) == 'Hm_lpvt_' || substr($cookie_key, 0, 5) == '_csrf') {
                continue;
            }
            $content[] = $cookie_key . '=' . $cookie_val;
            $cookie_data .= ' huke88.com	TRUE	/	FALSE	' . (time() + 2592000) . '	' . $cookie_key . '	' . $cookie_val . PHP_EOL;
        }

        $post['content'] = implode('; ', $content);

        $attach = Cookie::where('id', '>', 0)->find();

        if (empty($attach)){
            Cookie::create($post);
        }else{
            $attach->content= $post['content'];
            $attach->save();
        }

        if (!is_dir(runtime_path() . '../site_cookie/')) {
            @mkdir(runtime_path() . '../site_cookie', 0777);
        }
        file_put_contents(runtime_path() . '../site_cookie/cookie_1', $cookie_data);

        return show_success('cookie添加成功', 'admin/portal/cookie');
    }
}
